const { contextBridge, ipcRenderer } = require('electron')
const axios = require('axios')
const FormData = require('form-data')
const fs = require('fs')

// 创建 axios 实例
const request = axios.create({
  baseURL: 'http://localhost:8080/api',
  timeout: 30000
})

// 响应拦截器
request.interceptors.response.use(
  response => {
    const res = response.data
    if (res.code === 0) {
      return res.data
    }
    return Promise.reject(res.msg || '请求失败')
  },
  error => {
    console.error('请求错误:', error)
    return Promise.reject(error.message || '请求失败')
  }
)

contextBridge.exposeInMainWorld('electron', {
  // 系统信息相关
  getSystemInfo: () => ipcRenderer.invoke('get-system-info'),
  getSystemLoad: () => ipcRenderer.invoke('get-system-load'),
  exportSystemInfo: () => ipcRenderer.invoke('export-system-info'),
  
  // 文件管理相关
  getDirectories: (dirPath) => ipcRenderer.invoke('get-directories', dirPath),
  getFiles: (dirPath) => ipcRenderer.invoke('get-files', dirPath),
  
  // 设置相关
  loadSettings: () => ipcRenderer.invoke('load-settings'),
  saveSettings: (settings) => ipcRenderer.invoke('save-settings', settings),
  
  // 证件照相关
  getPhotoSizes: async () => {
    try {
      return await request.get('/photo/sizes')
    } catch (error) {
      throw new Error('获取照片尺寸失败: ' + error.message)
    }
  },
  
  processIdPhoto: async (params) => {
    try {
      // 将 base64 图片数据转换为文件
      const base64Data = params.portraitUrl.replace(/^data:image\/\w+;base64,/, '')
      const tempPath = `temp_${Date.now()}.jpg`
      fs.writeFileSync(tempPath, base64Data, 'base64')
      
      // 创建 FormData
      const formData = new FormData()
      formData.append('file', fs.createReadStream(tempPath))
      formData.append('size', params.size)
      formData.append('background', params.background)
      if (params.options && params.options.length > 0) {
        params.options.forEach(option => {
          formData.append('options', option)
        })
      }
      
      // 发送请求
      const processedUrl = await request.post('/photo/process', formData, {
        headers: formData.getHeaders()
      })
      
      // 清理临时文件
      fs.unlinkSync(tempPath)
      
      return {
        success: true,
        processedUrl
      }
    } catch (error) {
      return {
        success: false,
        error: error.message
      }
    }
  },
  
  saveProcessedImage: async (imageUrl, filename) => {
    try {
      // 下载处理后的图片
      const response = await request.get(imageUrl, { responseType: 'arraybuffer' })
      const buffer = Buffer.from(response.data)
      
      // 弹出保存对话框
      const result = await ipcRenderer.invoke('save-dialog', {
        title: '保存证件照',
        defaultPath: filename,
        filters: [{ name: '图片文件', extensions: ['jpg'] }]
      })
      
      if (result.canceled) {
        return { success: false, error: '用户取消保存' }
      }
      
      // 保存文件
      fs.writeFileSync(result.filePath, buffer)
      return {
        success: true,
        filePath: result.filePath
      }
    } catch (error) {
      return {
        success: false,
        error: error.message
      }
    }
  },
  
  exportPrintFile: async (params) => {
    try {
      const printUrl = await request.post('/photo/export-print', null, { params })
      return {
        success: true,
        printUrl
      }
    } catch (error) {
      return {
        success: false,
        error: error.message
      }
    }
  },
  
  // 监听器
  onSettingsUpdated: (callback) => ipcRenderer.on('settings-updated', callback),
  onPerformanceUpdate: (callback) => ipcRenderer.on('performance-update', callback)
}) 